import 'package:cbec_app/utils/EventMgr.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

import '../../../components/http/network.dart';

///app主路由控制器
class MainController extends GetxController {
  //首页
  static const String mainBottomNavRouteNameHome = 'home';
  //分类
  static const String mainBottomNavRouteNameClassify = 'classify';
  //会员界面
  static const String mainBottomNavRouteNameMember = 'member';
  //购物车
  static const String mainBottomNavRouteNameBags = 'bags';
  //个人中心
  static const String mainBottomNavRouteNameMy = 'my';

  late CupertinoTabController tabController;
  var navIndex = 0;

  // 是否展示会员模块
  bool allowMember = false;

  void onNavClick(int index) {
    navIndex = index;
    update();
  }

  @override
  void onInit() async {
    super.onInit();

    tabController = CupertinoTabController(initialIndex: 0);
    String? routeName = Get.arguments;
    if (routeName != null) {
      onToBottomNav(routeName);
    }

    ///监听路由
    EventMgr.on(EventType.exchangeNav, (arg) {
      onToBottomNav(arg);
      UmengCommonSdk.onEvent('Tab', {'routeName': arg});
    });

    await getDefaultInfoConfig();
  }

  ///监听跳转底部导航栏
  void onToBottomNav(String routeName) {
    switch (routeName) {
      case mainBottomNavRouteNameClassify:
        tabController.index = 1;
        break;
      case mainBottomNavRouteNameMember:
        tabController.index = 2;
        break;
      case mainBottomNavRouteNameBags:
        if (allowMember) {
          tabController.index = 3;
        } else {
          tabController.index = 2;
        }
        break;
      case mainBottomNavRouteNameMy:
        if (allowMember) {
          tabController.index = 4;
        } else {
          tabController.index = 3;
        }
        break;
      default:
        tabController.index = 0;
    }
    update();
  }

  @override
  void onClose() {
    EventMgr.off(EventType.exchangeNav);
    super.onClose();
  }

  /// 是否展示会员模块
  Future getDefaultInfoConfig() async {
    await Network.getDefaultInfo().then((value) {
      allowMember = value['allowMember'] != 0;
      print('是否展示会员模块 === $allowMember');
      update();
    }).catchError((error) {});
  }
}
